import { Application } from "egg";
import WeWorkBaseService from "./WeWorkBaseService";
import { WeWork } from "./type";
import CodoError from "../CodoError";

export default class Department extends WeWorkBaseService {
	constructor(
		protected config: WeWork.IWeWorkConfig,
		private accessToken: string,
		protected app: Application
	) {
		super(config, app);
	}
	/** 查询企业的全部部门
	 *  - https://developer.work.weixin.qq.com/document/path/90208
	 */
	async getAllList() {
		const url = `https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=${this.accessToken}`;
		type response = { department: WeWork.IDepartmentList[] } & WeWork.IResponse;
		const res = await this.curl<response>(url, {
			method: "GET",
			dataType: "json",
		});
		if (res.data.errcode === 0) {
			return res.data.department;
		}
		this.app.logger.error("[企业微信，查询部门列表] 失败 %s", res.data.errmsg);
		throw new CodoError(res.data.errmsg);
	}

	/**
	 *创建部门
	 * @param {qwInterface.IDepartmentCreate} data 创建部门的数据
	 * @memberof PlatformQiyeWeixinDepartmentService
	 * - https://developer.work.weixin.qq.com/document/path/90205
	 */
	async create(data: WeWork.IDepartmentCreate) {
		const url = `https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token=${this.accessToken}`;
		type response = { id: number } & WeWork.IResponse;
		const res = await this.curl<response>(url, {
			method: "POST",
			dataType: "json",
			contentType: "json",
			data,
		});
		const res2 = res.data;
		if (res2.errcode === 0) {
			return res2.id;
		} else {
			this.app.logger.error("[企业微信，创建部门] 失败 %s", res2.errmsg);
			throw new CodoError(res2.errmsg);
		}
	}

	/**
	 *删除部门 部门不能含有子部门、成员
	 *
	 * @param {number} id 部门id
	 * @memberof PlatformQiyeWeixinDepartmentService
	 */
	async delete(id: number) {
		const url = `https://qyapi.weixin.qq.com/cgi-bin/department/delete?access_token=${this.accessToken}&id=${id}`;
		const response = await this.curl<WeWork.IResponse>(url, {
			method: "GET",
			dataType: "json",
		});
		if (response.data.errcode === 0) {
			return true;
		} else {
			this.app.logger.error("[企业微信 删除部门] 错误 %s", response.data.errmsg);
			throw new CodoError(response.data.errmsg);
		}
	}
}
